package org.javaboy.oauth2.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.ldapAuthentication()
                .userSearchBase("ou=test")
                .userSearchFilter("(cn={0})")
                .contextSource()
                .url("ldap://127.0.0.1:3268/DC=lianglm,DC=net?cn?sub?(&(objectClass=organizationalPerson))")
                .managerDn("CN=Administrator,CN=Users,DC=lianglm,DC=net")
                .managerPassword("passwd");
    }

//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable().formLogin();
//    }
//}
    @Autowired
    private CustomerCorsFilter customerCorsFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/login", "/oauth/authorize", "/oauth/token", "/oauth/check_token","/*")
                .permitAll().anyRequest().authenticated().and().formLogin().permitAll()
                .and()
                .csrf().disable().addFilterBefore(customerCorsFilter, WebAsyncManagerIntegrationFilter.class);
    }
}